<template>
  <div class="execution-controls">
    <div class="mb-3">
      <p class="text-xs text-gray-500 mb-2">执行控制</p>
      
      <div class="grid grid-cols-4 gap-2">
        <!-- 下一步执行 -->
        <el-button
          size="small"
          type="info"
          :disabled="!canExecuteNext || isExecuting"
          @click="executeNextStep"
          class="execution-btn"
        >
          <el-icon class="mr-1"><i-ep-d-arrow-right /></el-icon>
          下一步
        </el-button>

        <!-- 运行全部 -->
        <el-button
          size="small"
          type="primary"
          :loading="isExecuting"
          :disabled="!hasSteps || isExecuting"
          @click="executeAll"
          class="execution-btn"
        >
          <el-icon class="mr-1"><i-ep-video-play /></el-icon>
          运行全部
        </el-button>

        <!-- 暂停/继续 -->
        <el-button
          size="small"
          :type="executionStatus === 'paused' ? 'success' : 'warning'"
          :disabled="!canPauseOrResume"
          @click="togglePauseResume"
          class="execution-btn"
        >
          <el-icon class="mr-1">
            <i-ep-video-pause v-if="executionStatus === 'running'" />
            <i-ep-video-play v-else />
          </el-icon>
          {{ executionStatus === 'running' ? '暂停' : '继续' }}
        </el-button>

        <!-- 重置 -->
        <el-button
          size="small"
          type="danger"
          :disabled="executionStatus === 'idle'"
          @click="resetExecution"
          class="execution-btn"
        >
          <el-icon class="mr-1"><i-ep-refresh-left /></el-icon>
          重置
        </el-button>
      </div>
    </div>

    <!-- 执行状态显示 -->
    <div v-if="showExecutionStatus" class="execution-status">
      <div 
        class="status-card p-3 rounded-md border text-sm"
        :class="getExecutionStatusClasses()"
      >
        <div class="flex items-center justify-between mb-2">
          <div class="flex items-center">
            <el-icon class="mr-2 status-icon" :class="getStatusIconClasses()">
              <component :is="getStatusIcon()" />
            </el-icon>
            <span class="font-medium">{{ getExecutionStatusText() }}</span>
          </div>
          <div class="text-xs text-gray-500">
            {{ formatDuration(executionDuration) }}
          </div>
        </div>

        <!-- 进度条 -->
        <div v-if="hasSteps" class="mb-2">
          <div class="flex justify-between text-xs text-gray-500 mb-1">
            <span>进度: {{ completedSteps }}/{{ totalSteps }}</span>
            <span>成功率: {{ successRate.toFixed(1) }}%</span>
          </div>
          <el-progress 
            :percentage="progressPercentage" 
            :status="getProgressStatus()"
            :show-text="false"
            :stroke-width="6"
          />
        </div>

        <!-- 统计信息 -->
        <div class="grid grid-cols-3 gap-3 text-xs">
          <div class="text-center">
            <div class="font-medium text-green-600">{{ successfulSteps }}</div>
            <div class="text-gray-500">成功</div>
          </div>
          <div class="text-center">
            <div class="font-medium text-red-600">{{ failedSteps }}</div>
            <div class="text-gray-500">失败</div>
          </div>
          <div class="text-center">
            <div class="font-medium text-gray-600">{{ pendingSteps }}</div>
            <div class="text-gray-500">待执行</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 执行日志 -->
    <div v-if="showExecutionLog && executionResults.length > 0" class="execution-log mt-3">
      <div class="text-xs text-gray-500 mb-2">执行日志</div>
      <div class="log-container max-h-32 overflow-y-auto border border-gray-200 rounded-md">
        <div
          v-for="result in executionResults.slice(-5)"
          :key="result.stepNumber"
          class="log-entry p-2 text-xs border-b border-gray-100 last:border-b-0"
          :class="result.success ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'"
        >
          <div class="flex items-center justify-between">
            <span class="font-medium">
              步骤 {{ result.stepNumber }}: 
              {{ result.success ? '成功' : '失败' }}
            </span>
            <span class="text-gray-400">
              {{ formatTime(result.timestamp) }}
            </span>
          </div>
          <div v-if="result.error" class="mt-1 text-red-600">
            {{ result.error }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useScriptStore } from '../stores/script'
import { useExecutionStore } from '../stores/execution'
import { ElMessage, ElMessageBox } from 'element-plus'

// Element Plus 图标
import {
  DArrowRight as iEpDArrowRight,
  VideoPlay as iEpVideoPlay,
  VideoPause as iEpVideoPause,
  RefreshLeft as iEpRefreshLeft,
  Loading as iEpLoading,
  Check as iEpCheck,
  Warning as iEpWarning,
  Close as iEpClose
} from '@element-plus/icons-vue'

const props = defineProps({
  showExecutionStatus: {
    type: Boolean,
    default: true
  },
  showExecutionLog: {
    type: Boolean,
    default: true
  }
})

const scriptStore = useScriptStore()
const executionStore = useExecutionStore()

// 计算属性
const hasSteps = computed(() => scriptStore.hasSteps)
const totalSteps = computed(() => scriptStore.stepCount)
const isExecuting = computed(() => executionStore.isExecuting)
const executionStatus = computed(() => executionStore.executionStatus)
const currentStepIndex = computed(() => executionStore.currentStepIndex)
const executionResults = computed(() => executionStore.executionResults)
const successfulSteps = computed(() => executionStore.successfulSteps)
const failedSteps = computed(() => executionStore.failedSteps)
const executionDuration = computed(() => executionStore.executionDuration)
const successRate = computed(() => executionStore.successRate)

const canExecuteNext = computed(() => {
  return hasSteps.value && currentStepIndex.value < totalSteps.value - 1 && !isExecuting.value
})

const canPauseOrResume = computed(() => {
  return executionStatus.value === 'running' || executionStatus.value === 'paused'
})

const completedSteps = computed(() => {
  return successfulSteps.value + failedSteps.value
})

const pendingSteps = computed(() => {
  return totalSteps.value - completedSteps.value
})

const progressPercentage = computed(() => {
  if (totalSteps.value === 0) return 0
  return (completedSteps.value / totalSteps.value) * 100
})

// 方法
const executeNextStep = async () => {
  const nextIndex = currentStepIndex.value + 1
  if (nextIndex < scriptStore.steps.length) {
    const step = scriptStore.steps[nextIndex]
    try {
      const result = await executionStore.executeStep(step)
      if (result.success) {
        ElMessage.success(`步骤 ${step.stepNumber} 执行成功`)
      } else {
        ElMessage.error(`步骤 ${step.stepNumber} 执行失败`)
      }
    } catch (error) {
      ElMessage.error(`执行失败: ${error.message}`)
    }
  }
}

const executeAll = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要执行全部 ${totalSteps.value} 个步骤吗？`,
      '确认执行',
      {
        confirmButtonText: '执行',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await executionStore.executeAllSteps(scriptStore.steps)
    if (result.success) {
      ElMessage.success(`执行完成，成功 ${successfulSteps.value} 个，失败 ${failedSteps.value} 个`)
    } else {
      ElMessage.error(`执行失败: ${result.message}`)
    }
  } catch {
    // 用户取消执行
  }
}

const togglePauseResume = () => {
  if (executionStatus.value === 'running') {
    executionStore.pauseExecution()
    ElMessage.info('执行已暂停')
  } else if (executionStatus.value === 'paused') {
    executionStore.resumeExecution()
    ElMessage.info('执行已继续')
  }
}

const resetExecution = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置执行状态吗？所有执行结果将被清除。',
      '确认重置',
      {
        confirmButtonText: '重置',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    executionStore.resetExecution()
    ElMessage.success('执行状态已重置')
  } catch {
    // 用户取消重置
  }
}

const getExecutionStatusClasses = () => {
  switch (executionStatus.value) {
    case 'running':
      return 'border-blue-200 bg-blue-50 text-blue-700'
    case 'paused':
      return 'border-yellow-200 bg-yellow-50 text-yellow-700'
    case 'completed':
      return failedSteps.value > 0 
        ? 'border-orange-200 bg-orange-50 text-orange-700'
        : 'border-green-200 bg-green-50 text-green-700'
    case 'failed':
      return 'border-red-200 bg-red-50 text-red-700'
    default:
      return 'border-gray-200 bg-gray-50 text-gray-700'
  }
}

const getStatusIconClasses = () => {
  switch (executionStatus.value) {
    case 'running':
      return 'text-blue-500 animate-spin'
    case 'paused':
      return 'text-yellow-500'
    case 'completed':
      return failedSteps.value > 0 ? 'text-orange-500' : 'text-green-500'
    case 'failed':
      return 'text-red-500'
    default:
      return 'text-gray-400'
  }
}

const getStatusIcon = () => {
  switch (executionStatus.value) {
    case 'running':
      return iEpLoading
    case 'paused':
      return iEpWarning
    case 'completed':
      return failedSteps.value > 0 ? iEpWarning : iEpCheck
    case 'failed':
      return iEpClose
    default:
      return iEpWarning
  }
}

const getExecutionStatusText = () => {
  switch (executionStatus.value) {
    case 'running':
      return '执行中...'
    case 'paused':
      return '已暂停'
    case 'completed':
      return failedSteps.value > 0 ? '执行完成（有失败）' : '执行成功'
    case 'failed':
      return '执行失败'
    default:
      return '就绪'
  }
}

const getProgressStatus = () => {
  if (failedSteps.value > 0) return 'exception'
  if (executionStatus.value === 'completed') return 'success'
  return undefined
}

const formatDuration = (duration) => {
  if (duration < 1000) return `${duration}ms`
  return `${(duration / 1000).toFixed(1)}s`
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString()
}
</script>

<style scoped>
.execution-btn {
  width: 100%;
  font-size: 12px;
}

.status-card {
  transition: all 0.3s ease;
}

.status-icon {
  transition: all 0.3s ease;
}

.log-container {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.log-entry {
  transition: all 0.2s ease;
}

.log-entry:hover {
  background-color: rgba(0, 0, 0, 0.05);
}
</style>
